package com.cheetah.start.module.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cheetah.start.module.system.domain.SysAdmin;
import com.cheetah.start.module.system.domain.SysRole;
import com.cheetah.start.module.system.domain.SysRoleAdmin;
import com.cheetah.start.module.system.mapper.SysRoleAdminMapper;
import com.cheetah.start.module.system.service.ISysRoleAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 系统角色管理服务impl
 *
 * @author Feel
 * @date 2021/10/17
 */
@Service
public class SysRoleAdminServiceImpl extends ServiceImpl<SysRoleAdminMapper, SysRoleAdmin> implements ISysRoleAdminService {

    @Autowired
    private SysRoleAdminMapper roleAdminMapper;

    @Override
    public List<String> getRoleCodeByAdminId(Integer adminId) {
        return roleAdminMapper.getByAdminId(adminId);
    }

    @Override
    public List<SysRole> getByAdminId(Integer adminId) {
        return roleAdminMapper.getRoleByAdminId(adminId);
    }

    @Override
    public boolean saveBySysAdmin(SysAdmin sysAdmin) {
        String roleIds = sysAdmin.getRoleIds();
        if (StrUtil.isBlank(roleIds)) {
            return true;
        }
        Integer adminId = sysAdmin.getAdminId();
        String[] roleIdArr = roleIds.split(",");
        List<SysRoleAdmin> roleAdmins = new ArrayList<>();
        if (roleIdArr.length > 0) {
            for (String roleId : roleIdArr) {
                SysRoleAdmin roleAdmin = new SysRoleAdmin();
                roleAdmin.setAdminId(adminId);
                roleAdmin.setRoleId(Integer.parseInt(roleId));
                roleAdmin.setCreateTime(new Date());
                roleAdmins.add(roleAdmin);
            }
        }
        return saveBatch(roleAdmins);
    }

    @Override
    public boolean removeByAdminId(Integer adminId) {
        return removeByColVal("admin_id", adminId);
    }

    @Override
    public boolean removeByRoleId(Integer roleId) {
        return removeByColVal("role_id", roleId);
    }

    @Override
    public boolean removeByColVal(String col, Object val) {
        QueryWrapper<SysRoleAdmin> wrapper = new QueryWrapper<>();
        wrapper.eq(col, val);
        return remove(wrapper);
    }
}
